package damngoodcoffee.smart;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.google.inject.Inject;

import damngoodcoffee.smart.commands.Command;

public class ParserImpl implements Parser {
    private static Logger logger = Logger.getLogger(ParserImpl.class
	    .getCanonicalName());
    private XMLReader parser;
    private SmartContentHandler contentHandler;
    private ResourceReader reader;

    @Inject
    public ParserImpl(XMLReader parser, SmartContentHandler contentHandler,
	    ResourceReader reader) {
	super();
	this.parser = parser;
	this.contentHandler = contentHandler;
	this.reader = reader;
    }

    public List<Command> parse(String source) throws ParserException {
	try {
	    contentHandler.reset();
	    parser.setContentHandler(contentHandler);
	    parser.parse(new InputSource(reader.read(source)));
	    return contentHandler.getCommands();
	} catch (IOException e) {
	    throw new ParserException(e);
	} catch (SAXException e) {
	    throw new ParserException(e);
	} catch (ResourceReaderException e) {
	    throw new ParserException(e);
	}
    }
}
